package com.neusoft.nepa.controller;

import com.neusoft.nepa.entity.User;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.PasswordField; // 建议使用 PasswordField
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class AdminLoginViewController {
    @FXML
    private TextField userName;
    @FXML
    private PasswordField passcode; // 改为 PasswordField 避免密码明文显示

    @FXML
    public void login(ActionEvent event) {
        System.out.println("login");
        File file = new File("Admin.txt");

        // 1. 检查文件是否存在
        if (!file.exists()) {
            System.out.println("文件不存在");
            showAlert(Alert.AlertType.ERROR, "文件不存在", "用户数据文件 Admin.txt 不存在");
            return;
        }

        // 2. 检查文件是否为空
        if (file.length() == 0) {
            showAlert(Alert.AlertType.ERROR, "文件为空", "用户数据文件为空，请先注册用户");
            return;
        }

        // 3. 安全读取文件（包裹在 try-catch 中）
        Map<String, User> userMap = new HashMap<>(); // 假设文件中存储的是 String -> User 的映射
        try (FileInputStream fis = new FileInputStream(file);
             ObjectInputStream ois = new ObjectInputStream(fis)) {
            userMap = (HashMap<String, User>) ois.readObject();
            System.out.println("userMap 的键类型：" + userMap.keySet().iterator().next().getClass().getName());
            System.out.println("userMap 中的第一个键：" + userMap.keySet().iterator().next());
        } catch (EOFException e) {
            showAlert(Alert.AlertType.ERROR, "文件格式错误", "用户数据文件格式错误，读取到文件末尾");
            return;
        } catch (IOException | ClassNotFoundException e) {
            showAlert(Alert.AlertType.ERROR, "读取失败", "读取用户数据失败：" + e.getMessage());
            e.printStackTrace();
            return;
        }

        // 4. 处理特殊指令（示例：显示所有用户）
        if ("hello,future".equals(userName.getText())) {
            showAllUsers(userMap);
            return;
        }

        // 5. 用户验证逻辑（优化版）
        String inputUsername = userName.getText();
        String inputPassword = passcode.getText();
        User matchedUser = null;

        // 先尝试按用户名匹配
        matchedUser = userMap.get(inputUsername);
        if (matchedUser != null && matchedUser.getPasscode().equals(inputPassword)) {
            handleLoginSuccess(matchedUser, event);
            return;
        }

        // 再尝试按电话号码匹配（优化异常处理）
        try {
            String phoneNumber = inputUsername;
            for (User user : userMap.values()) {
                if (user.getPhoneNumber() .equals(phoneNumber) && user.getPasscode().equals(inputPassword)) {
                    matchedUser = user;
                    handleLoginSuccess(matchedUser, event);
                    return;
                }
            }
        } catch (NumberFormatException e) {
            // 非数字输入，不做处理，继续执行
        }

        // 6. 未匹配到用户
        showAlert(Alert.AlertType.ERROR, "登录失败", "用户名/密码错误或用户不存在");
    }

    // 显示所有用户信息（提取为独立方法）
    private void showAllUsers(Map<String, User> userMap) {
        if (userMap.isEmpty()) {
            showAlert(Alert.AlertType.INFORMATION, "用户列表", "当前没有注册用户");
            return;
        }

        StringBuilder sb = new StringBuilder("所有用户信息：\n\n");
        for (User user : userMap.values()) {
            sb.append("用户名：").append(user.getUserName()).append("\n");
            sb.append("密码：").append(user.getPasscode()).append("\n"); // 注意：实际项目中密码不应明文显示
            sb.append("电话：").append(user.getPhoneNumber()).append("\n\n");
        }

        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("用户列表");
        alert.setContentText(sb.toString());
        alert.showAndWait();
    }

    // 处理登录成功（提取为独立方法）
    private void handleLoginSuccess(User user, ActionEvent event) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("欢迎");
        alert.setContentText("欢迎回来，" + user.getUserName());
        alert.showAndWait();

        try {
            Stage stage = (Stage) ((javafx.scene.Node) event.getSource()).getScene().getWindow();
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/com/neusoft/nepa/view/AdminView.fxml"));
            Parent parent = fxmlLoader.load();
            Scene newScene = new Scene(parent, 960, 540);
            stage.getProperties().put("userName",user.getUserName());
            stage.getProperties().put("userInfo", user);
            stage.setTitle("NorthEast Software Corporation Public Supervisor Platform Manage System");
            stage.setScene(newScene);
            stage.show();
        } catch (IOException e) {
            showAlert(Alert.AlertType.ERROR, "界面跳转失败", "跳转主界面失败：" + e.getMessage());
        }
    }

    // 统一提示方法（提取为独立方法）
    private void showAlert(Alert.AlertType type, String title, String content) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setContentText(content);
        alert.showAndWait();
    }

    public void handleRegister(ActionEvent event) throws IOException {
        Stage stage = (Stage) ((javafx.scene.Node) event.getSource()).getScene().getWindow();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/neusoft/nepa/view/AdminRegisterView.fxml"));
        Parent fxmlContent = loader.load();

        BackgroundPane backgroundPane = new BackgroundPane();
        backgroundPane.getChildren().add(fxmlContent);
        fxmlContent.setStyle("-fx-background-color: transparent;");
        Scene newScene = new Scene(backgroundPane, 960, 540);
        stage.setScene(newScene);
        stage.setResizable(false);
        stage.setTitle("Register");
        stage.show();
    }
}